<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="器具编码" prop="containerCode">
        <el-input
          v-model="queryParams.containerCode"
          placeholder="请输入器具编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="操作类型" prop="operationType">
        <el-select v-model="queryParams.operationType" placeholder="请选择操作类型" clearable multiple>
          <el-option
            v-for="(label, value) in operationTypeOptions"
            :key="value"
            :label="label"
            :value="value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作仓库" prop="warehouseId">
        <el-select v-model="queryParams.warehouseId" placeholder="请选择仓库" clearable>
          <el-option
            v-for="warehouse in warehouseOptions"
            :key="warehouse.value"
            :label="warehouse.label"
            :value="warehouse.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="操作时间" prop="operationTimeRange">
        <el-date-picker
          v-model="operationTimeRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          :picker-options="pickerOptions"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作按钮区域 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['pack:container:operation:log:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据列表区域 -->
    <el-table v-loading="loading" :data="operationLogList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="记录ID" align="center" prop="logId" width="80" />
      <el-table-column label="器具编码" align="left" prop="container.containerCode" width="120">
        <template slot-scope="scope">
          <el-link type="primary" @click="handleContainerDetail(scope.row.container)">
            {{ scope.row.container ? scope.row.container.containerCode : '-' }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="操作类型" align="center" prop="operationType" width="100">
        <template slot-scope="scope">
          <el-tag :class="'operation-type-' + scope.row.operationType" size="small">
            {{ operationTypeOptions[scope.row.operationType] || '未知' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作仓库" align="left" prop="warehouse.warehouseName" width="160" :show-overflow-tooltip="true" />
      <el-table-column label="操作时间" align="center" prop="operationTime" width="160">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operationTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="left" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleViewDetail(scope.row)"
            v-hasPermi="['pack:container:operation:log:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-location"
            @click="handleLocation(scope.row)"
            v-if="scope.row.latitude && scope.row.longitude"
          >定位</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页导航区域 -->
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 操作详情弹窗 -->
    <el-drawer
      title="操作详情"
      :visible.sync="detailOpen"
      direction="rtl"
      size="50%"
      custom-class="drawer-container"
    >
      <div class="drawer-content">
        <operation-detail :detail-data="detailData" />
      </div>
    </el-drawer>

    <!-- 导出配置弹窗 -->
    <el-dialog title="导出配置" :visible.sync="exportOpen" width="600px" append-to-body>
      <export-config @confirm="confirmExport" @cancel="exportOpen = false" />
    </el-dialog>
  </div>
</template>

<script>
import { searchContainerOperationLog, getContainerOperationLog, getFilterOptions, exportContainerOperationLog } from "@/api/pack/containerOperationLog";
import OperationDetail from "./components/OperationDetail";
import ExportConfig from "./components/ExportConfig";

export default {
  name: "ContainerOperationLog",
  components: {
    OperationDetail,
    ExportConfig
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 器具操作记录表格数据
      operationLogList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 详情弹窗
      detailOpen: false,
      // 详情数据
      detailData: {},
      // 导出弹窗
      exportOpen: false,
      // 操作时间范围
      operationTimeRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        containerCode: null,
        operationType: [],
        warehouseId: null,
        operationTimeStart: null,
        operationTimeEnd: null,
        companyId: null
      },
      // 筛选选项
      operationTypeOptions: {},
      warehouseOptions: [],
      operatorOptions: [],
      // 日期选择器选项
      pickerOptions: {
        shortcuts: [{
          text: '今天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 0);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '昨天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 1);
            end.setTime(end.getTime() - 3600 * 1000 * 24 * 1);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近7天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近30天',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '本月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setDate(1);
            start.setHours(0, 0, 0, 0);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '上月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setMonth(start.getMonth() - 1);
            start.setDate(1);
            start.setHours(0, 0, 0, 0);
            end.setMonth(end.getMonth() - 1);
            end.setDate(0);
            end.setHours(23, 59, 59, 999);
            picker.$emit('pick', [start, end]);
          }
        }]
      }
    };
  },
  created() {
    this.getList();
    this.getFilterOptions();
  },
  methods: {
    /** 查询器具操作记录列表 */
    getList() {
      this.loading = true;
      
      // 处理时间范围
      if (this.operationTimeRange && this.operationTimeRange.length === 2) {
        this.queryParams.operationTimeStart = this.operationTimeRange[0];
        this.queryParams.operationTimeEnd = this.operationTimeRange[1];
      } else {
        this.queryParams.operationTimeStart = null;
        this.queryParams.operationTimeEnd = null;
      }
      
      // 创建查询参数副本，处理空数组
      const params = { ...this.queryParams };
      if (params.operationType && params.operationType.length === 0) {
        delete params.operationType;
      }
      
      searchContainerOperationLog(params).then(response => {
        this.operationLogList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    
    /** 获取筛选条件选项 */
    getFilterOptions() {
      getFilterOptions().then(response => {
        this.operationTypeOptions = response.data.operationTypeOptions || {};
        this.warehouseOptions = response.data.warehouseOptions || [];
        this.operatorOptions = response.data.operatorOptions || [];
      });
    },
    
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    
    /** 重置按钮操作 */
    resetQuery() {
      this.operationTimeRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.logId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    
    /** 查看详情 */
    handleViewDetail(row) {
      this.detailData = row;
      this.detailOpen = true;
    },
    
    /** 查看器具详情 */
    handleContainerDetail(container) {
      if (container && container.containerId) {
        this.$router.push({
          path: '/pack/container',
          query: { containerId: container.containerId }
        });
      }
    },
    
    /** 定位显示 */
    handleLocation(row) {
      if (row.latitude && row.longitude) {
        // 这里可以集成地图组件显示位置
        this.$message.info(`位置：${row.latitude}, ${row.longitude}`);
      }
    },
    
    /** 导出按钮操作 */
    handleExport() {
      this.exportOpen = true;
    },
    
    /** 确认导出 */
    confirmExport(config) {
      this.exportLoading = true;
      this.exportOpen = false;
      
      const params = {
        ...this.queryParams,
        exportFields: config.selectedFields
      };
      
      // 处理空数组
      if (params.operationType && params.operationType.length === 0) {
        delete params.operationType;
      }
      
      exportContainerOperationLog(params).then(response => {
        this.$download.excel(response, '器具操作记录.xlsx');
        this.exportLoading = false;
      }).catch(() => {
        this.exportLoading = false;
      });
    }
  }
};
</script>

<style scoped>
/* 操作类型标签样式 */
.operation-type-1 { background-color: #e6f7ff; color: #1890ff; }
.operation-type-2 { background-color: #f6ffed; color: #52c41a; }
.operation-type-3 { background-color: #fff2e8; color: #fa8c16; }
.operation-type-4 { background-color: #f0f5ff; color: #722ed1; }
.operation-type-5 { background-color: #e6fffb; color: #13c2c2; }
.operation-type-6 { background-color: #f6ffed; color: #52c41a; }
.operation-type-7 { background-color: #fff2e8; color: #fa8c16; }
.operation-type-8 { background-color: #fff1f0; color: #f5222d; }
.operation-type-9 { background-color: #f6ffed; color: #52c41a; }
.operation-type-10 { background-color: #fff7e6; color: #fa541c; }
.operation-type-11 { background-color: #f0f5ff; color: #2f54eb; }

.el-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.drawer-container {
  position: relative;
  height: 100%;
}

.drawer-content {
  padding: 20px;
  height: calc(100% - 60px);
  overflow-y: auto;
}

.drawer-footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  padding: 10px 20px;
  background-color: #fff;
  border-top: 1px solid #e8e8e8;
  text-align: right;
}
</style> 